/**
 * 认证相关API接口
 */

import { request } from '@/utils/request'
import type {
  ApiResponse,
  LoginRequest,
  LoginResponse,
  User,
  UserPermissionInfo
} from '@/types/rbac'

// API路径前缀
const API_PREFIX = '/api/v1/auth'

/**
 * 认证API
 */
export const authApi = {
  /**
   * 用户登录
   */
  async login(credentials: LoginRequest): Promise<ApiResponse<LoginResponse>> {
    return request.post(`${API_PREFIX}/login`, credentials)
  },

  /**
   * 用户登出
   */
  async logout(): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/logout`)
  },

  /**
   * 刷新访问令牌
   */
  async refreshToken(refreshToken: string): Promise<ApiResponse<{
    access_token: string
    refresh_token: string
    token_type: string
    expires_in: number
  }>> {
    return request.post(`${API_PREFIX}/refresh`, { refresh_token: refreshToken })
  },

  /**
   * 获取当前用户信息
   */
  async getCurrentUser(): Promise<ApiResponse<User>> {
    return request.get(`${API_PREFIX}/me`)
  },

  /**
   * 获取当前用户权限
   */
  async getUserPermissions(): Promise<ApiResponse<UserPermissionInfo>> {
    return request.get(`${API_PREFIX}/me/permissions`)
  },

  /**
   * 修改密码
   */
  async changePassword(data: {
    old_password: string
    new_password: string
    confirm_password: string
  }): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/change-password`, data)
  },

  /**
   * 忘记密码 - 发送重置邮件
   */
  async forgotPassword(email: string): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/forgot-password`, { email })
  },

  /**
   * 重置密码
   */
  async resetPassword(data: {
    token: string
    new_password: string
    confirm_password: string
  }): Promise<ApiResponse> {
    return request.post(`${API_PREFIX}/reset-password`, data)
  },

  /**
   * 验证令牌
   */
  async verifyToken(token?: string): Promise<ApiResponse<{
    valid: boolean
    user?: User
  }>> {
    return request.post(`${API_PREFIX}/verify-token`, { token })
  },

  /**
   * 更新用户资料
   */
  async updateProfile(data: Partial<User>): Promise<ApiResponse<User>> {
    return request.put(`${API_PREFIX}/profile`, data)
  },

  /**
   * 上传头像
   */
  async uploadAvatar(file: File): Promise<ApiResponse<{ avatar_url: string }>> {
    return request.upload(`${API_PREFIX}/avatar`, file)
  },

  /**
   * 获取验证码
   */
  async getCaptcha(): Promise<ApiResponse<{
    session_id: string
    captcha_image: string
  }>> {
    return request.post(`${API_PREFIX}/captcha`, {})
  },

  /**
   * 验证验证码
   */
  async verifyCaptcha(sessionId: string, captchaCode: string): Promise<ApiResponse<{
    valid: boolean
  }>> {
    return request.post(`${API_PREFIX}/verify-captcha`, {
      session_id: sessionId,
      captcha_code: captchaCode
    })
  }
}

export default authApi